/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package pub.pjoc.pay.channels;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import pub.pjoc.pay.channels.annotation.PayType;

import java.util.HashMap;
import java.util.Map;

/**
 * @author blademainer
 * @version 2016-10-11 23:00
 */
@Service
public class PayTypeContainer implements ApplicationListener<ContextRefreshedEvent> {
  private static final Logger logger = LoggerFactory.getLogger(PayTypeContainer.class);
  private Map<String, AbstractPayChannel> payTypeMap;

  public AbstractPayChannel getPayChannelByPayType(String payType) {
    Assert.notNull(payType, "Pay type must not be null!");
    if (payTypeMap == null) {
      logger.error("Pay type map does'nt initialized!");
      return null;
    }
    AbstractPayChannel abstractPayChannel = payTypeMap.get(payType);
    if (abstractPayChannel != null) {
      if (logger.isDebugEnabled()) {
        logger.debug("Return pay channel: {} by pay type: {}", abstractPayChannel, payType);
      }
    } else {
      logger.warn("Not found match pay type: {}", payType);
    }
    return abstractPayChannel;
  }

  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    Class<PayType> annotationClass = PayType.class;
    payTypeMap = new HashMap<>();

    ApplicationContext applicationContext = event.getApplicationContext();
    Map<String, AbstractPayChannel> beansOfType = applicationContext.getBeansOfType(AbstractPayChannel.class);
    System.out.println(beansOfType);
    Map<String, Object> payTypes = applicationContext.getBeansWithAnnotation(annotationClass);

    if (logger.isDebugEnabled()) {
      logger.debug("Found pay type map: {}", payTypes);
    }
    payTypes.forEach((beanName, object) -> {
      // Get annotation.
      PayType annotation = object.getClass().getAnnotation(annotationClass);
      String payType = annotation.value();


      if (!(object instanceof AbstractPayChannel)) {
        logger.error("Error process pay type: {} that object: {} is not instance of "
            + "AbstractPayChannel!", payType, object);
        return;
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Found pay type: {} with channel: {}", payType, object);
      }
      payTypeMap.put(payType, (AbstractPayChannel) object);
    });

  }

}
